package com.heima.juc.n8;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author : leimingchao
 * @date Date : 2022年02月20日 20:08
 */
@Slf4j(topic = "c.TestCyclicBarrier")
public class TestCyclicBarrier {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        //test(pool);
        //test2(pool);

        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            log.debug("task1 task2 finish...");
        });

        for (int i = 0; i < 3; i++) {
            pool.submit(() -> {
                log.debug("task1 begin...");
                Sleeper.sleep(1);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });

            pool.submit(() -> {
                log.debug("task2 begin...");
                Sleeper.sleep(2);
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }

        pool.shutdown();
    }

    private static void test2(ExecutorService pool) {
        for (int i = 0; i < 3; i++) {
            CountDownLatch countDownLatch = new CountDownLatch(2);

            pool.submit(() -> {
                log.debug("task1 start...");
                Sleeper.sleep(1);
                countDownLatch.countDown();
            });

            pool.submit(() -> {
                log.debug("task2 start...");
                Sleeper.sleep(2);
                countDownLatch.countDown();
            });

            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.debug("task1 task2 finish...");
        }
    }

    private static void test(ExecutorService pool) {
        CountDownLatch countDownLatch = new CountDownLatch(2);

        pool.submit(() -> {
            log.debug("task1 start...");
            Sleeper.sleep(1);
            countDownLatch.countDown();
        });

        pool.submit(() -> {
            log.debug("task2 start...");
            Sleeper.sleep(2);
            countDownLatch.countDown();
        });

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.debug("task1 task2 finish...");
    }
}
